package com.example.mp3player;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class FileBrowser extends ListActivity {
	private File currentDir;
	private FileArrayAdapter adapter;
	Thread thr;
	Context context;
	boolean chooseFile;
	ArrayList<Integer> folderID = new ArrayList<Integer>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		
		/*	Set actionbar */
		ActionBar actionbar = getActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		
		/*	Get external storage directory (Default is /sdcard/)	*/
		currentDir = Environment.getExternalStorageDirectory();	
		
		ListView list = getListView();
	    list.setOnItemLongClickListener(new OnItemLongClickListener() {

	    	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
	    		Option item = adapter.getItem(position);
	    		try{
	    			addFolder(item);
	    		}catch(Exception e){
	    			e.getStackTrace();
	    		}
	    		return true;
	    	}
	    });
		
		/*	Get files in a separate thread	*/
		thr = new Thread(getFilesAndFolders);
		thr.start();
	}

	Runnable getFilesAndFolders = new Runnable(){
		public void run() {
			fill(currentDir);
		}
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// if icon in action bar is clicked; go home
			thr = null;		//Kill thread
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	//--------------------------------------------------------//
	/*					Fill View Method					*/
	//--------------------------------------------------------//

	/*	Get files and folders 	*/
	private void fill(File f){
		File[] dirs = f.listFiles();
		this.setTitle("Current Dir: "+f.getName());

		List<Option> dir = new ArrayList<Option>();
		List<Option> fls = new ArrayList<Option>();

		/* Go through all files and folders	*/
		for(File ff: dirs){
			if(ff.isDirectory()){
				dir.add(new Option(ff.getName(), "Folder", ff.getAbsolutePath()));
			}
			/*	Get only mp3-files	*/
			else if(ff.getName().endsWith(".mp3")){
				fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
			}
			else{
				System.out.println("No files/folders");
			}
		}
		/*	Sort folders and files in alphabetic order	*/
		Collections.sort(dir);
		Collections.sort(fls);

		/*	add all files and folders to view	*/
		dir.addAll(fls);

		/*	Set go back button	*/
		if(!f.getName().equalsIgnoreCase(Environment.getExternalStorageDirectory().getName()))
			dir.add(0, new Option("..", "Parent Directory", f.getParent()));

		/*	Set ListAdapter	*/
		adapter = new FileArrayAdapter(FileBrowser.this, R.layout.file_view, dir);
		runOnUiThread(new Runnable() {
			public void run() {
				((ListActivity) context).setListAdapter(adapter);
			}
		});
	}

	//--------------------------------------------------------//
	/*					onClick Methods						*/
	//--------------------------------------------------------//

	@Override
	/*	If item is clicked	*/
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Option item = adapter.getItem(position);
		/*	if true, try get new path	*/
		if(item.getData().equalsIgnoreCase("folder") || item.getData().equalsIgnoreCase("parent directory")){
			try{
				currentDir = new File(item.getPath());
				thr.run();
			}catch(Exception e){
				e.getStackTrace();
			}
		}
		/*	If file */
		else{
			onFileClick(item);
		}
	}

	/*	OnLongClick add folder	*/
	private void addFolder(Option item){
		ArrayList<String> songs = new ArrayList<String>();
		
		int count = 0;
		File[] tmp = new File(item.getPath()).listFiles();
		for(File ff: tmp){
			/*	Get only mp3-files	*/
			if(ff.getName().endsWith(".mp3")){
				songs.add(ff.getPath());
				count++;
			}
		}
		Toast.makeText(this, "Folder added: "+item.getName()+"\nAdded "+count+" songs.", Toast.LENGTH_SHORT).show();
		
		/* Send information to main activity and finish()	*/
		Intent intent = new Intent();
		intent.putExtra("requestCode", 1);
		intent.putStringArrayListExtra("songList", songs);
		
		setResult(Activity.RESULT_OK, intent);
		thr = null;
		finish();
	}

	private void onFileClick(Option item){
		Toast.makeText(this, "File Clicked: "+item.getName(), Toast.LENGTH_SHORT).show();

		/*	Send information to main activity and finish()	*/
		Intent intent = new Intent();
		intent.putExtra("requestCode", 0);
		intent.putExtra("song", item.getPath());
		setResult(Activity.RESULT_OK, intent);
		thr = null;
		finish();
	}
	
}
